package com.giantlizard.cloud.common.security.service.impl;

import com.giantlizard.cloud.base.generics.R;
import com.giantlizard.cloud.common.security.constants.SecurityConstants;
import com.giantlizard.cloud.common.security.constants.TokenConstants;
import com.giantlizard.cloud.common.security.model.LoginUser;
import com.giantlizard.cloud.common.security.service.TokenService;
import com.giantlizard.cloud.common.security.utils.JwtTokenUtil;
import com.giantlizard.cloud.redis.utils.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Token验证处理
 */
@Service
public class TokenServiceImpl implements TokenService {
    
    private final RedisOperator redisService;

    public TokenServiceImpl(RedisOperator redisService) {
        this.redisService = redisService;
    }

    /**
     * 创建令牌
     */
    @Override
    public String createToken(LoginUser loginUser) {
        String token = JwtTokenUtil.generateToken(loginUser);
        loginUser.setToken(token);
        refreshToken(loginUser);
        return token;
    }
    
    /**
     * 获取用户身份信息
     */
    @Override
    public LoginUser getLoginUser(String token) {
        if (token == null) {
            return null;
        }
        String userKey = getTokenKey(token);
        return redisService.getCacheObject(userKey);
    }
    
    /**
     * 删除用户身份信息
     */
    @Override
    public void delLoginUser(String token) {
        if (token != null) {
            String userKey = getTokenKey(token);
            redisService.delKey(userKey);
        }
    }
    
    /**
     * 验证令牌有效期
     */
    @Override
    public Boolean verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= TokenConstants.REFRESH_TIME) {
            refreshToken(loginUser);
            return true;
        }
        return false;
    }
    
    /**
     * 刷新令牌有效期
     */
    @Override
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + TokenConstants.TOKEN_EXPIRATION);
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setObj(userKey, loginUser, TokenConstants.TOKEN_EXPIRATION);
    }
    
    private String getTokenKey(String token) {
        return SecurityConstants.LOGIN_TOKEN_KEY + token;
    }
} 